package com.chinafree.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by wangjiaxin on 2019/11/12.
 * json工具类
 */
public class JsonUtils {
    /**
     * 递归读取所有的key
     *
     * @param jsonObject
     */
    public static List<Object> getAllKey(JSONObject jsonObject) {
        List<Object> keyList = new ArrayList<Object>();
        Iterator<String> keys = jsonObject.keySet().iterator();// jsonObject.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            keyList.add(key.toString());
            if (jsonObject.get(key) instanceof JSONObject) {
                JSONObject innerObject = (JSONObject) jsonObject.get(key);
                keyList.add(getAllKey(innerObject));
            } else if (jsonObject.get(key) instanceof JSONArray) {
                JSONArray innerObject = (JSONArray) jsonObject.get(key);
                keyList.add(getAllKey(innerObject));
            }
        }
        return keyList;
    }
    public static Object getAllKey(JSONArray json1) {
        List<Object> keyList = new ArrayList<Object>();
        if (json1 != null ) {
            Iterator i1 = json1.iterator();
            while (i1.hasNext()) {
                Object key = i1.next();
                if (key instanceof  JSONObject) {
                    JSONObject innerObject = (JSONObject) key;
                    keyList.add(getAllKey(innerObject));
                } else if (key instanceof JSONArray) {
                    JSONArray innerObject = (JSONArray) key;
                    keyList.add(getAllKey(innerObject));
                }else{
                }
            }
        }
        return keyList;
    }

    public static String writeValueAsString(Object s){
        return JSON.toJSONString(s);
    }


}
